<?php
namespace pc\controllers;

use common\helpers\Image;
use common\models\StarRanking;
use common\Service\RedisService;
use pc\models\Banner;
use pc\models\News;
use pc\models\Portray;
use pc\models\Star;
use pc\models\Tags;
use phpDocumentor\Reflection\DocBlock\Tag;
use Yii;
use pc\controllers\BaseController;
use yii\helpers\ArrayHelper;

/**
 * Site controller
 */
class SiteController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ]
        ];
    }

    public function init()
    {
        parent::init();
        $model = new Banner();
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $hostInfo = strtolower(Yii::$app->request->getHostInfo());
        if(stripos($hostInfo,'www') === false){
            $this->redirect('http://www.guotuw.com',301);
        }

        $params['banners'] = Banner::getBannersByStatic(3);

        //banner右侧新闻
        $params['latestNews'] = News::pageNews(1,5,['id','title'])['data'];
        $maxViewNews = News::getMaxViewNews(1,12,['id','title','image'])['data'];
        $params['hotNews'] = $params['imgNews'] = $rs = [];
        //去重
        if($maxViewNews){
            $outIds = array_column($params['latestNews'],'id');
            foreach ($maxViewNews as $newInfo){
                !in_array($newInfo['id'],$outIds) && $rs[] = $newInfo;
            }
        }
        //只保留需要的数据
        if($rs){
            $params['hotNews'] = array_slice($rs,0,5);
            count($rs) > 5 && $params['imgNews'] = array_slice($rs,5,2);
        }

        //首页美女写真
        $params['portrays'] = Portray::randomPortrays(8,['id','title']);


        $starModel = new StarRanking();
        $starFields = ['id','name','nick_name','header','view','desc','tags'];
        $params['indexMaxStar'] = $this->indexMaxStar();
        //最新更新的美女
        $params['latestStars'] = Star::randomStars(6,[],[$params['indexMaxStar']['id']]);
        //处理属性
        $params['latestStars'] = $this->createStarAttributeLabels($params['latestStars']);
        //美女周榜
        $params['weekStars'] = $starModel->pageRanking(StarRanking::RANKING_WEEK,1,5,$starFields)['data'];
        //美女月榜
        $params['monthStars'] = $starModel->pageRanking(StarRanking::RANKING_MONTH,1,5,$starFields)['data'];

        $portraysFields = ['id','title','desc','tags','create_time'];
        //写真周榜
        $params['weekPortrays'] = Portray::recommendPortrays(5,$portraysFields);
        //写真月榜
        $params['monthPortrays'] =Portray::randomPortrays(5,$portraysFields,array_column($params['weekPortrays'],'id'));

        return $this->render('index',$params);
    }




    private function createStarAttributeLabels($stars){
        //max 6
        $sortAttributes = ['birthday','star_sign','country','birth_place','job','size','interest','height','weight','blood_type','animal','tags'];
        $model = new Star();
        $attributeLabels  = $model->attributeLabels();

        foreach ($stars as $key => $star){
            $countAttribute = 0;
            $attributeString = '';
            foreach ($sortAttributes as $attribute){
                if($countAttribute > 4) break;
                if($attribute == 'country') continue;

                if(isset($star[$attribute]) && !empty($star[$attribute])){
                    $attributeString .= '<p>'.$attributeLabels[$attribute].':';

                    if(in_array($attribute,['birth_place','job','interest','tags'])){
                        $tags = $attribute == 'birth_place' ? Tags::parseTagsByName($star['country']) : Tags::parseTagsByName($star[$attribute]);
                        if($tags){
                            $tmp  = $attribute == 'birth_place' ? $star['country'] : '';
                            $tmp .= $star[$attribute];
                            foreach ($tags as $tagInfo){
                                $tmp = str_replace($tagInfo['name'],"<a style='color:#f69;' href='/meinv/{$tagInfo['alias']}/' title ='{$tagInfo['name']}美女'>{$tagInfo['name']}</a>",$tmp);
                            }
                            $attributeString .= $tmp;
                            unset($tmp);
                        }else{
                            $attributeString .= $star[$attribute];
                        }
                    }else{
                        if($attribute == 'birthday'){
                            $attributeString .= date("Y-m-d",$star[$attribute]);
                        }else if($attribute == 'star_sign'){
                            $attributeString .= "<a style='color:#f69;' target='_blank' href='/meinv/".Yii::$app->params['starSignAlias'][$star[$attribute]]."/' title ='".Yii::$app->params['starSign'][$star[$attribute]]."美女'>".Yii::$app->params['starSign'][$star[$attribute]]."</a>";
                        }else if($attribute == 'height'){
                            $attributeString .= $star[$attribute].'CM';
                        }else if($attribute == 'weight'){
                            $attributeString .= $star[$attribute].'KG';
                        }else if($attribute == 'blood_type'){
                            $attributeString .= $star[$attribute].'型';
                        }else{
                            $attributeString .= $star[$attribute];
                        }
                    }
                    unset($stars[$key][$attribute]);
                    $attributeString .= '</p>';
                    $countAttribute++;

                }
            }

            $stars[$key]['attributeString'] = $attributeString;
        }
        return $stars;
    }

    public function actionXiaoxifu(){
        $id = (int)Yii::$app->request->get('id');
        $redis = Yii::$app->get('redis');
        if((int)$redis->exists('star:'.$id)){
            $redis->set('indexMaxStar',$id);
            $redis->expire('indexMaxStar',3 * 60 * 60);
            echo '恭喜你更换成功。';
            exit;
        }
        echo 'Oop,ID错误了。';
    }

    private function indexMaxStar(){
        $starId = Yii::$app->get('redis')->get('indexMaxStar');

        $needFields = ['id','name','nick_name','header','tags'];

        $starInfo = Star::getStarInfoById($starId,$needFields);
        if(empty($starInfo)){
            $starInfo = Star::randomStars(1,$needFields)[0];
            Yii::$app->get('redis')->set('indexMaxStar',$starInfo['id']);
            Yii::$app->get('redis')->expire('indexMaxStar',3 * 60 * 60);
        }
        return $starInfo;
    }



    public function actionAddPortray(){
        $id = (int)Yii::$app->request->get('pid');
        if($id > 0){
            $model = new Banner();
            $model->addPortrayBanner($id);
        }
    }
}
